import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState, Dispatch } from "@/store";
import tools from "@/util/tools";

interface Pages {
  pageNum: number;
  pageSize: number;
}
interface SearchOptions {
  id?: number | string;
  name?: string;
}
export default function useCardData(
  pages: Pages,
  searchOptions: SearchOptions
) {
  const dispatch = useDispatch<Dispatch>();

  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);

  const [loading, setLoading] = useState(false);

  async function getData() {
    setLoading(true);
    const res = await dispatch.card.getData(
      tools.clearNull({ ...pages, ...searchOptions })
    );
    if (res?.status === 200) {
      setList(res.data.list);
      setTotal(res.data.total);
    }
    setLoading(false);
  }

  async function addData(options: any) {
    setLoading(true);
    const res = await dispatch.card.add(options);
    if (res?.status === 200) {
      getData();
    }
    setLoading(false);
    return res;
  }

  async function updateData(options: any) {
    setLoading(true);
    const res = await dispatch.card.update(options);
    if (res?.status === 200) {
      getData();
    }
    setLoading(false);
    return res;
  }

  async function deleteData(id: number | string) {
    setLoading(true);
    const res = await dispatch.card.delete(id);
    if (res?.status === 200) {
      getData();
    }
    setLoading(false);
    return res;
  }

  useEffect(() => {
    getData();
  }, [pages.pageNum, pages.pageSize]);

  return {
    list,
    total,
    loading,
    getData,
    addData,
    updateData,
    deleteData,
  };
}
